import React from "react";
import {Button, Modal, Menu,Table, ConfigProvider, Divider} from "antd/lib";
import ContractAmount from "@/services/contractamount";
import CreateAmountDialog from "@/components/contract/new/AmountDialog";
import notification from "@/services/notification";
import {get} from "lodash";
import zhCN from 'antd/es/locale/zh_CN';
import GlobalSetting from "@/services/globalsetting";
import { find } from "lodash";
import { Query } from "@/services/query";
import VisualizationRenderer from "@/components/visualizations/VisualizationRenderer";
import WarningOutlined from "@ant-design/icons/WarningOutlined";

const { confirm } = Modal;
export default class LookAmount extends React.Component {
    state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    data: [],
    kqflag:true,
    queryid:0,
    visualizationid:0,
    query:null,
    visualization:null,
    queryresults:null,
    error:null,
    openpage:"kxjh",
  };
 componentWillMount() {
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      contractsid: this.props.id,
    }
   this.refreshData(param);
   param={
      page: 1,
      pagesize: 5,
      code: '款项url',
      type: '合同主页面',
    }

    GlobalSetting.getlist(param).then(data => {
      const ids = data.data[0].value.split(',');
      const qid = Number(ids[0]);
      let vid= ids.length>1 ? Number(ids[1]):0;
      if(qid>0){
        Query.get({ id: qid })
        .then(result => {
            let vistion=result.visualizations[0];
            if (vid>0){
                vistion = find(result.visualizations, vis => vis.id === vid);
            }
            if(result.options.parameters.length>0){
              result.options.parameters[0].value=this.props.code;
            }
            this.setState({
              queryid:qid,
              visualizationid:vid,
              query:result,
              visualization:vistion,
              error:null,
            });
            this.refreshQueryResults(result);
        })
        .catch(error => {
          this.setState({
            error: error.message +":" + error.detailedMessage,
          });
        });
      }
    });

  }
  refreshQueryResults = (query) =>{
    if (query) {
      query
        .getQueryResultPromise()
        .then(result => {
          this.setState({
            queryresults:result,
            error:null,
          });
        })
        .catch(error => {
          this.setState({
            error: error.message +":" + error.detailedMessage,
          });
        });
    }
  };
  refreshData = (params) => {
    // let param={
    //   page: this.state.page,
    //   pagesize: this.state.pagesize,
    //   contractsid: this.props.id,
    // }
    ContractAmount.getlist(params).then(data => {
      this.setState({
        data:data.data,
        page: params.page,
        pagesize: params.pagesize,
        total: data.total,
      });
    });
  }
  handleadd = () => {
       this.showCreateAmountDialog(0);
  };
//   kqflagchange= () => {
//     const flags= !this.state.kqflag;
//     this.setState({
//       kqflag:flags,
//     });
// };
  handleUpdate = record => {
     this.showCreateAmountDialog(record.id);
  };

  handleDelete = record => {
    confirm({
      title: '确定删除款项?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractAmount.delete(record).then(()=>{
          notification.success("款项删除成功.");
          let param={
              page: 1,
              pagesize: this.state.pagesize,
              contractsid: this.props.id,
            }
           this.refreshData(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  showCreateAmountDialog = (id) => {
    CreateAmountDialog.showModal({amount_id: id,contractsid:this.props.id})
    .onClose((result = {}) => {
        if (result.success) {
          let param={
              page: 1,
              pagesize: this.state.pagesize,
              contractsid: this.props.id,
            }
           this.refreshData(param);
        }
      }).onDismiss(() => {
       // navigateTo("orgstruct", true);
      });
  };
   handleTableChange = (pagination, filters, sorter) => {
    let param={
      page: pagination.current,
      pagesize: pagination.pageSize,
      contractsid: this.props.id,
    }
    this.refreshData(param);
  };
  tabsClick = e => {
    this.setState({
      openpage: e.key,
      kqflag: e.key==="kxjh" ? true:false,
    });
  };
    render() {
      if (this.state.loading) return null;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '款项类型',
        key: 'typename',
        dataIndex: 'typename',
        render: (text, record) => (
            <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
        ),
      },
      {
        title: '计划日期',
        dataIndex: 'bill_date',
        key: 'bill_date',
      },
      {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
      },
      // {
      //   title: '执行金额',
      //   dataIndex: 'finishamount',
      //   key: 'finishamount',
      // },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
             <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
      return (
          <ConfigProvider locale={zhCN}>
             <div>
                {/* <Button type="primary" onClick={() => this.kqflagchange()} >
                  <i className="fa fa-search m-r-5" />
                  {this.state.kqflag ? "联查HRP":"款项计划"}
                </Button> */}
                <Menu onClick={this.tabsClick} selectedKeys={this.state.openpage} mode="horizontal">
                  <Menu.Item key = "kxjh">款项计划</Menu.Item>
                  <Menu.Item key = "lchrp">联查HRP</Menu.Item>
                </Menu>
                {this.state.kqflag && (
                  <Divider type="vertical" /> )}
                {this.state.kqflag && (
                  <Button type="primary" onClick={() => this.handleadd()}>
                  <i className="fa fa-plus m-r-5" />
                  新增
                </Button>)}
                {this.state.kqflag && (
                 <Table rowKey='id'
                         columns={listcolumns}
                         dataSource={this.state.data}
                         pagination={paginationProps}
                         loading={this.state.loading}
                         onChange={this.handleTableChange}
                  />
                )}
              {!this.state.kqflag && this.state.error && <div className="alert alert-danger" data-test="ErrorMessage">{`Error: ${this.state.error}`}</div>}
              {!this.state.kqflag && !this.state.error && this.state.queryresults && (
                <VisualizationRenderer 
                visualization={this.state.visualization} 
                queryResult={this.state.queryresults} context="query" />
              )}
             </div>
         </ConfigProvider>
      );
    }
}
